const serverAddress = window.location.origin + "/sf";

function updateNumberDisplays(counts) {
    const countDisplays = document.querySelectorAll(".count-display");
    updateDisplay(counts.ct_count, countDisplays[0], countDisplays[0].parentElement);
    updateDisplay(counts.ct_online_filter_count, countDisplays[1], countDisplays[1].parentElement);
    updateDisplay(counts.ct_online_count, countDisplays[2], countDisplays[2].parentElement);
    updateDisplay(counts.cm_count, countDisplays[3], countDisplays[3].parentElement);
    updateDisplay(counts.cm_online_filter_count, countDisplays[4], countDisplays[4].parentElement);
    updateDisplay(counts.cm_online_count, countDisplays[5], countDisplays[5].parentElement);
    updateDisplay(counts.cu_count, countDisplays[6], countDisplays[6].parentElement);
    updateDisplay(counts.cu_online_filter_count, countDisplays[7], countDisplays[7].parentElement);
    updateDisplay(counts.cu_online_count, countDisplays[8], countDisplays[8].parentElement);
    updateDisplay(counts.total_count, countDisplays[9], countDisplays[9].parentElement);
    updateDisplay(counts.online_filter_count, countDisplays[10], countDisplays[10].parentElement);
    updateDisplay(counts.online_count, countDisplays[11], countDisplays[11].parentElement);
    updateDisplay(counts.unknown_online_count, countDisplays[12], countDisplays[12].parentElement);
    updateDisplay(counts.custom_count, countDisplays[13], countDisplays[13].parentElement);
}

function updateBandwidthDisplays(counts) {
    const bandwidthDisplays = document.querySelectorAll(".bandwidth-display");
    updateDisplay(counts.ct_bandwidth, bandwidthDisplays[0], bandwidthDisplays[0].parentElement);
    updateDisplay(counts.cm_bandwidth, bandwidthDisplays[1], bandwidthDisplays[1].parentElement);
    updateDisplay(counts.cu_bandwidth, bandwidthDisplays[2], bandwidthDisplays[2].parentElement);
    updateDisplay(counts.custom_bandwidth, bandwidthDisplays[3], bandwidthDisplays[3].parentElement);
}

function updateDisplay(number, numDisplay, groupDisplays) {
    // 如果数字有变化，添加动画效果
    if (numDisplay.textContent !== number) {
        gsap.to(groupDisplays, {
            opacity: 0, y: -50, duration: 0.8, onComplete: () => {
                numDisplay.textContent = number;
                gsap.to(groupDisplays, {
                    opacity: 1, y: 0, duration: 0.8, ease: "power2.out",
                });
            },
        });
    } else {
        numDisplay.textContent = number;
    }
}

// 停止按钮处理
function setupStopButton() {
    const stopButton = document.querySelector(".red-bg");
    if (!stopButton) return;
    stopButton.addEventListener("click", async () => {
        if (!confirm('你确定要执行 "停止" 操作吗？')) {
            return;
        }
        // 按钮置灰
        stopButton.disabled = true;
        const originalText = stopButton.innerText;
        stopButton.innerText = "处理中...";

        try {
            const formData = new FormData();
            formData.append("isp", "CUSTOM");
            const response = await fetch(serverAddress + "/Flow/Stop", {
                method: "POST", body: formData,
            });
            if (!response.ok) {
                console.error("HTTP error! status:", response.status);
            }
            const result = await response.json();
            if (result && result.code === 200) {
                alert("操作成功");
            } else {
                alert(`操作异常: ${result.message || "未知错误"}`);
            }
        } catch (error) {
            alert(`操作异常: ${error.message}`);
        } finally {
            // 恢复按钮状态
            stopButton.disabled = false;
            stopButton.innerText = originalText;
        }
    });
}

// 测试按钮处理
function setupTestButton() {
    const testButton = document.querySelector(".yellow-bg");
    if (!testButton) return;
    testButton.addEventListener("click", async () => {
        // 查找对应的输入框（同一区域内的.input-field）
        const inputField = testButton
            .closest(".button-box")
            ?.querySelector(".input-field");
        const addrInput = document.querySelector('[name="addr"]');
        if (!inputField || !addrInput) {
            alert("未找到输入框");
            return;
        }
        const uid = inputField.value.trim();
        const addr = addrInput.value.trim();
        if (!uid || !addr) {
            alert("请输入测试参数");
            if (!uid) inputField.focus(); else if (!addr) addrInput.focus();
            return;
        }
        if (!confirm('你确定要执行 "测试" 操作吗？')) {
            return;
        }
        // 按钮置灰
        testButton.disabled = true;
        const originalText = testButton.innerText;
        testButton.innerText = "处理中...";
        try {
            const formData = new FormData();
            formData.append("uid", uid);
            formData.append("addr", addr);
            const response = await fetch(serverAddress + "/Flow/Test", {
                method: "POST", body: formData,
            });
            if (!response.ok) {
                console.error("HTTP error! status:", response.status);
            }
            const result = await response.json();
            if (result && result.code === 200) {
                alert("操作成功");
            } else {
                alert(`操作异常: ${result.message || "未知错误"}`);
            }
        } catch (error) {
            alert(`操作异常: ${error.message}`);
        } finally {
            // 恢复按钮状态
            testButton.disabled = false;
            testButton.innerText = originalText;
        }
    });
}

// 开始按钮处理
function setupStartButton() {
    const startButton = document.querySelector(".green-bg");
    if (!startButton) return;
    startButton.addEventListener("click", async () => {
        // 查找同一区域内的三个输入框（通过name属性精确选择）
        const durationInput = startButton
            .closest(".button-box")
            ?.querySelector('[name="duration"]');
        const rateInput = startButton
            .closest(".button-box")
            ?.querySelector('[name="rate"]');
        const limitInput = startButton
            .closest(".button-box")
            ?.querySelector('[name="limit"]');
        const addrInput = document.querySelector('[name="addr"]');
        if (!durationInput || !rateInput || !limitInput || !addrInput) {
            alert("未找到输入框");
            return;
        }
        const duration = durationInput.value.trim();
        const rate = rateInput.value.trim();
        const limit = limitInput.value.trim();
        const addr = addrInput.value.trim();
        if (!duration || !rate || !limit || !addr) {
            alert("请填写所有参数");
            // 高亮未填写的输入框
            if (!duration) durationInput.focus(); else if (!rate) rateInput.focus(); else if (!limit) limitInput.focus(); else if (!addr) addrInput.focus();
            return;
        }
        if (!confirm('你确定要执行 "开始" 操作吗？')) {
            return;
        }
        // 按钮置灰
        startButton.disabled = true;
        const originalText = startButton.innerText;
        startButton.innerText = "处理中...";
        try {
            const formData = new FormData();
            formData.append("duration", duration);
            formData.append("rate", rate);
            formData.append("limit", limit);
            formData.append("addr", addr);
            const response = await fetch(serverAddress + "/Flow/Start", {
                method: "POST", body: formData,
            });
            if (!response.ok) {
                console.error("HTTP error! status:", response.status);
            }
            const result = await response.json();
            if (result && result.code === 200) {
                alert("操作成功");
            } else {
                alert(`操作异常: ${result.message || "未知错误"}`);
            }
        } catch (error) {
            alert(`操作异常: ${error.message}`);
        } finally {
            // 恢复按钮状态
            startButton.disabled = false;
            startButton.innerText = originalText;
        }
    });
}

// 定期获取数据
function startServerCheck() {
    let i = 0;
    setInterval(async () => {
        // if (i % 3 === 2) {
        //   getCount().then();
        // }
        getCount().then();
        getBandwidth().then();
        i++;
    }, 30000); // 每10秒执行一次
}

async function getCount() {
    try {
        const response = await fetch(serverAddress + "/Flow/Count", {
            method: "GET", headers: {
                "Content-Type": "application/json",
            },
        });
        if (!response.ok) {
            console.error("HTTP error! status:", response.status);
        }
        const result = await response.json();
        if (result && result.code === 200) {
            updateNumberDisplays(result.data);
        } else {
            console.warn("Invalid response format:", result);
        }
    } catch (error) {
        updateNumberDisplays({
            custom_count: -1,
            ct_count: -1,
            cm_count: -1,
            cu_count: -1,
            total_count: -1,
            online_count: -1,
            ct_online_count: -1,
            cm_online_count: -1,
            cu_online_count: -1,
            online_filter_count: -1,
            ct_online_filter_count: -1,
            cm_online_filter_count: -1,
            cu_online_filter_count: -1,
            unknown_online_count: -1
        });
        console.error("get count failed:", error);
    }
}

async function getBandwidth() {
    try {
        const response = await fetch(serverAddress + "/Flow/Bandwidth", {
            method: "GET", headers: {
                "Content-Type": "application/json",
            },
        });
        if (!response.ok) {
            console.error("HTTP error! status:", response.status);
        }
        const result = await response.json();
        if (result && result.code === 200) {
            updateBandwidthDisplays(result.data);
        } else {
            console.warn("Invalid response format:", result);
        }
    } catch (error) {
        updateBandwidthDisplays({
            ct_bandwidth: -1,
            cm_bandwidth: -1,
            cu_bandwidth: -1,
            custom_bandwidth: -1
        });
        console.error("get bandwidth failed:", error);
    }
}

// 使用GSAP添加动画效果
function addAnimations() {
    // 标题动画
    gsap.from(".title-display", {
        duration: 1.2, scale: 0.5, opacity: 0, delay: 0.3, ease: "back.out(1.7)",
    });

    gsap.from(".group-display", {
        duration: 1.2, scale: 0.5, opacity: 0, delay: 0.3, ease: "back.out(1.7)",
    });

    // 按钮容器动画
    gsap.from(".button-box", {
        duration: 0.8, y: 30, opacity: 0, stagger: 0.2, delay: 0.6, ease: "power2.out",
    });
}

// 按钮点击动画
function setupButtonAnimations() {
    const buttons = document.querySelectorAll(".action-btn, .yellow-bg, .red-bg");

    buttons.forEach((button) => {
        button.addEventListener("mousedown", () => {
            gsap.to(button, {
                scale: 0.95, duration: 0.1,
            });
        });

        button.addEventListener("mouseup", () => {
            gsap.to(button, {
                scale: 1, duration: 0.2, ease: "back.out(2)",
            });
        });

        button.addEventListener("mouseleave", () => {
            gsap.to(button, {
                scale: 1, duration: 0.2,
            });
        });
    });
}

// 按钮聚焦动画
function setupButtonFocusAnimations() {
    const buttons = document.querySelectorAll(".action-btn, .yellow-bg, .red-bg");

    buttons.forEach((button) => {
        // 创建一个光晕效果元素
        const glow = document.createElement("div");
        glow.className = "button-glow";
        button.style.position = "relative";
        glow.style.position = "absolute";
        glow.style.top = "0";
        glow.style.left = "0";
        glow.style.width = "100%";
        glow.style.height = "100%";
        glow.style.setProperty("border-radius", "8px", "important");
        glow.style.pointerEvents = "none"; // 确保不会干扰按钮点击
        glow.style.opacity = "0";
        button.appendChild(glow);

        // 鼠标悬停时的动画
        button.addEventListener("mouseenter", () => {
            // 停止任何正在进行的动画
            gsap.killTweensOf(button);
            gsap.killTweensOf(glow);

            // 按钮弹跳效果
            gsap.to(button, {
                scale: 1.05, duration: 0.2, ease: "elastic.out(1.2, 0.4)",
            });

            // 光晕效果
            gsap.to(glow, {
                opacity: 0.6, boxShadow: "0 0 20px 5px " + getButtonColor(button), duration: 0.2,
            });
        });

        // 鼠标离开时的动画
        button.addEventListener("mouseleave", () => {
            gsap.to(button, {
                scale: 1, textShadow: "1px 1px 2px rgba(0, 0, 0, 0.3)", duration: 0.2, ease: "power2.out",
            });

            gsap.to(glow, {
                opacity: 0, boxShadow: "0 0 0px 0px rgba(255, 255, 255, 0)", duration: 0.2,
            });
        });
    });
}

// 根据按钮类型获取对应的光晕颜色
function getButtonColor(button) {
    if (button.classList.contains("action-btn")) {
        return "rgba(20, 200, 20, 0.7)";
    } else if (button.classList.contains("yellow-bg")) {
        return "rgba(255, 200, 0, 0.7)";
    } else if (button.classList.contains("red-bg")) {
        return "rgba(255, 100, 100, 0.7)";
    }
    return "rgba(255, 255, 255, 0.7)";
}

// 页面加载时初始化
document.addEventListener("DOMContentLoaded", function () {
    startServerCheck();
    setupStopButton();
    setupTestButton();
    setupStartButton();
    addAnimations(); // 添加动画效果
    setupButtonAnimations(); // 添加按钮点击动画
    setupButtonFocusAnimations(); // 添加按钮聚焦动画
    getCount().then();
    getBandwidth().then();
});

function isValidIP(str) {
    // 只校验IPv4格式
    const reg = /^(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)){3}$/;
    return reg.test(str);
}
